package com.ricky.cloud;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.netflix.hystrix.dashboard.EnableHystrixDashboard;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

/**
 * Created by baiguantao on 2017/10/27.
 */


@SpringBootApplication
@EnableDiscoveryClient
@RestController
@EnableCircuitBreaker //开启熔断器
@EnableHystrixDashboard
public class RibbonHystrixApplication {
    @LoadBalanced
    @Bean
    RestTemplate restTemplate(){
        return new RestTemplate();
    }

    @Autowired
    RestTemplate restTemplate;

    @RequestMapping("/hi")
    @HystrixCommand(fallbackMethod = "hifallback",
            commandProperties = {
                    @HystrixProperty(name="execution.isolation.strategy", value="SEMAPHORE")
            })
    public String hi(@RequestParam(value="name", defaultValue="ricky") String name) {
        String greeting = this.restTemplate.getForObject("http://eurekaclient/greeting", String.class);
        return String.format("%s, %s!", greeting, name);
    }
    public String hifallback(String name) {
        return String.format("%s, %s!", "hifallback", "default-ricky");
    }
    public static void main(String[] args) {
        new SpringApplicationBuilder(RibbonHystrixApplication.class)
                .web(true)
                .run(args);
    }
}
